package com.question.business.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.user.entity.UserPost;
import com.question.business.user.mapper.UserPostMapper;
import com.question.business.user.service.IUserPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 用户岗位服务实现类
 *
 * @author star
 * @since 2023-09-14
 */
@Slf4j
@Service
public class UserPostServiceImpl extends ServiceImpl<UserPostMapper, UserPost> implements IUserPostService {


    /**
     * 用户岗位查询
     *
     * @param userId 用户ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryPostByUserId(String userId) {
        return baseMapper.queryPostByUserId(userId);
    }

    /**
     * 岗位用户查询
     *
     * @param postId 岗位ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryUserByPostId(String postId) {
        return baseMapper.queryUserByPostId(postId);
    }

    /**
     * 用户岗位新增数据
     *
     * @param userId  用户ID
     * @param postIds 岗位ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserPost(String userId, List<String> postIds) {
        // 删除用户岗位
        baseMapper.deleteByUserId(userId);
        handleBatchAdd(Collections.singletonList(userId), postIds);
    }

    /**
     * 处理批量保存
     *
     * @param userIds 用户ID
     * @param postIds 岗位ID
     */
    private void handleBatchAdd(List<String> userIds, List<String> postIds) {
        if (CollectionUtils.isNotEmpty(userIds) && CollectionUtils.isNotEmpty(postIds)) {
            List<UserPost> data = new ArrayList<>();
            for (String userId : userIds) {
                for (String postId : postIds) {
                    UserPost entity = new UserPost();
                    entity.setUserId(userId);
                    entity.setPostId(postId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 岗位用户新增数据
     *
     * @param postId  岗位ID
     * @param userIds 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPostUser(String postId, List<String> userIds) {
        // 删除岗位用户
        baseMapper.deleteByPostId(postId);
        handleBatchAdd(userIds, Collections.singletonList(postId));
    }

}